// pages/kecheng_detail/kechengxiangqing/kechengxiangqing.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    courseDetail: {},
    obj_title:[],
    collectionClass:false,
    classChooseArr:['课程详情', '课程列表','名师介绍','课堂交流','课程评价'],
    classChooseIndex: 0,
    isShow:true,
    // 咨询师详情
		zxsXiangqing:{},
		discountPrice:0,
    fieldTagList:[],
    wendaMap:"",
		isCollected: false,  // 添加收藏状态
		courseId:0,
    courseList: [],      // 课件列表
    teacherInfo: null,     // 名师介绍
    communications: [], // 存储课堂交流问题列表
    currentPage: 1,
    pageSize: 10,
    hasMore: true,       // 是否还有更多数据
    loading: false,       // 是否正在加载
    hasBought: false,
    showShare: false,
    showReviewInput: false,
    newReview: {
      rating: 0,
      content: ''
    },
    replyContent: '', // 用户输入的回复内容
    currentQuestionId: null,
		isLoading: false,
		tempQuestionId:0,
  },
  
  filters: {
    noDecimal: function(value) {
      return Math.floor(value);
    }
  },
  lookMuch(){
    this.setData({
      isShow:false,
      obj_title:this.data.xqObj.periods
    })
  },
  sendIndex(e){
    const index = e.currentTarget.dataset.index;
    this.setData({
      classChooseIndex: index
    });

    // 当点击名师介绍时
    if (index === 2) {
      this.loadTeacherInfo(this.data.courseId);
      return;
    }

    // 根据索引获取对应类型的数据
    let type;
    switch(index) {
      case 1: type = 'list'; break;
      case 3: type = 'communication'; break;
      case 4: type = 'reviews'; break;
      default: return;
    }

    // 发送请求获取数据
    this.loadTypeData(type);
  },
  returnkecheng(){
    wx.navigateBack()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('课程ID:', options.id);
    const user = wx.getStorageSync('user');
    
    // 保存课程ID到data中
    this.setData({
      courseId: options.id
    });
    
    // 先检查收藏状态
    if (user.userId !=null) {
      this.checkCollectionStatus(options.id);
    }
    
    // 获取课程详情
    wx.request({
      url: `http://120.26.112.194:80/api/admin/courses/detail/${options.id}`,
      method: 'GET',
      success: (res) => {
        console.log('课程详情:', res.data);
        if (res.data && res.data.code === 200) {
          this.setData({
            courseDetail: res.data.data
					});
					this.getDiscountPrice()
        } else {
          wx.showToast({
            title: '获取详情失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });

    this.loadTeacherInfo(options.id);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.currentTab === 2) {
      this.setData({
        currentPage: 1,
        hasMore: true,
        communications: []
      }, () => {
        this.getCommunications();
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    if (this.data.classChooseIndex === 3) {
      this.setData({
        currentPage: 1,
        hasMore: true,
        communications: []
      }, () => {
        this.getCommunications();
        wx.stopPullDownRefresh();
      });
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 移除这个方法或保持空方法
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 检查收藏状态
  checkCollectionStatus(courseId) {
    const user = wx.getStorageSync('user');
    if (user.userId == null) return;

    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    wx.request({
      url: `http://120.26.112.194:80/api/admin/courses/checkCollect`,
      method: 'GET',
      data: {
        userId: user.userId,
        courseId: courseId
      },
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log('收藏状态检查结果:', res.data);
        if (res.data.code === 200) {
          this.setData({
						collectionClass: res.data.msg === "1"  // 使用 collectionClass 来控制收藏图标状态
          });
        }
      },
      fail: (err) => {
        console.error('检查收藏状态失败:', err);
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 收藏/取消收藏
  toggleCollect() {
    const user = wx.getStorageSync('user');
    const courseId = this.data.courseId;
    
    if (!user || !user.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    if (!courseId) {
      wx.showToast({
        title: '课程ID不存在',
        icon: 'none'
      });
      return;
    }

    // 根据当前收藏状态决定请求类型
		const isCurrentlyCollected = this.data.collectionClass;
		console.log(isCurrentlyCollected)
    const url = isCurrentlyCollected 
      ? `http://120.26.112.194:80/api/admin/courses/deleteCollect?userId=${user.userId}&courseId=${courseId}`
      : 'http://120.26.112.194:80/api/admin/courses/collect';

    wx.request({
      url: url,
      method: isCurrentlyCollected ? 'DELETE' : 'POST',
      data: {
        ...(!isCurrentlyCollected ? {
          userId: user.userId,
          courseId: courseId
        } : {})
      },
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log('收藏操作结果:', res.data);
        if (res.data.code === 200) {
          this.setData({
            collectionClass: !this.data.collectionClass  // 切换收藏状态
          });
          wx.showToast({
            title: res.data.msg || (this.data.collectionClass ? '收藏成功' : '取消收藏成功'),
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.msg || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('收藏操作失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 添加收藏按钮点击事件处理函数
  shoucangBtn() {
    this.toggleCollect();  // 调用已有的收藏切换方法
  },

  // 添加时间格式化方法
  formatReviewTime(timeStr) {
    const reviewTime = new Date(timeStr);
    const now = new Date();
    
    // 转换为时间戳（毫秒）
    const reviewTimestamp = reviewTime.getTime();
    const nowTimestamp = now.getTime();
    
    // 计算时间差（毫秒）
    const timeDiff = nowTimestamp - reviewTimestamp;
    const hoursDiff = Math.floor(timeDiff / (1000 * 60 * 60));
    
    // 是否是同一天
    const isToday = reviewTime.toDateString() === now.toDateString();
    
    // 是否是昨天
    const yesterday = new Date(now);
    yesterday.setDate(yesterday.getDate() - 1);
    const isYesterday = reviewTime.toDateString() === yesterday.toDateString();
    
    if (isToday) {
      if (hoursDiff < 1) {
        return '刚刚';
      }
      return `${hoursDiff}小时前`;
    } else if (isYesterday) {
      return '昨天';
    } else {
      // 格式化年月日
      const year = reviewTime.getFullYear();
      const month = String(reviewTime.getMonth() + 1).padStart(2, '0');
      const day = String(reviewTime.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  },

  // 加载不同类型的数据
  loadTypeData(type) {
    let url;
    switch(type) {
      case 'list':
        url = 'http://120.26.112.194:80/api/admin/courses/detailList';
        break;
      case 'communication':
        url = 'http://120.26.112.194:80/api/admin/courses/queryQuestion';
        break;
      case 'reviews':
        url = 'http://120.26.112.194:80/api/admin/courses/detailReviews';
        break;
      default:
        return;
    }

    // 获取用户信息
    const user = wx.getStorageSync('user');

    // 根据不同接口准备不同的请求参数
    let requestData;
    switch(type) {
      case 'reviews':
        requestData = {
          courseId: this.data.courseId,
          userId: user ? user.userId : ''
        };
        break;
      case 'communication':
        requestData = {
          courseId: this.data.courseId,
          page: this.data.currentPage,
          pageSize: this.data.pageSize
        };
        break;
      case 'list':
        requestData = {
          id: this.data.courseId
        };
        break;
    }

    wx.request({
      url: url,
      method: 'GET',
      data: requestData,
      success: (res) => {
        if (res.data.code === 200) {
          // 根据类型更新不同的数据
          switch(type) {
            case 'list':
              this.setData({ courseList: res.data.data });
              break;
            case 'communication':
              const newData = res.data.data.list;
              if (this.data.currentPage === 1) {
                this.setData({ 
                  communications: newData,
                  hasMore: !res.data.data.isLastPage
                });
              } else {
                this.setData({
                  communications: [...this.data.communications, ...newData],
                  hasMore: !res.data.data.isLastPage
                });
              }
              break;
            case 'reviews':
              // 处理评价时间
              const formattedReviews = res.data.data.map(review => ({
                ...review,
                reviewTime: this.formatReviewTime(review.reviewTime)
              }));
              this.setData({ reviews: formattedReviews });
              break;
          }
        } else {
          wx.showToast({
            title: '获取数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 查看回复
  toggleReply(e) {
    const questionId = e.currentTarget.dataset.id;
    const communications = this.data.communications;
    
    // 找到对应的问题并切换其回复显示状态
    const updatedCommunications = communications.map(item => {
      if (item.questionId === questionId) {
        // 如果还没有回复数据，则添加模拟数据
        if (!item.replies) {
          item.replies = [
            {
              replyId: 1,
              userName: "心理咨询师小王",
              replyTime: "2024-01-08 20:27",
              content: "这种情况是很常见的，建议可以..."
            },
            {
              replyId: 2,
              userName: "用户12345",
              replyTime: "2024-01-08 20:27",
              content: "我也遇到过类似的问题，后来是这样解决的..."
            }
          ];
        }
        return { ...item, showReplies: !item.showReplies };
      }
      return item;
    });

    this.setData({
      communications: updatedCommunications
    });
  },

  submitReply(e) {
    const questionId = e.currentTarget.dataset.id;
    const content = this.data.replyContent;
    
    if (!content.trim()) {
      wx.showToast({
        title: '请输入回复内容',
        icon: 'none'
      });
      return;
    }

    wx.request({
      url: 'http://120.26.112.194:80/api/admin/courses/addReply',
      method: 'POST',
      data: {
        questionId: questionId,
        replyContent: content,
        courseId: this.data.courseDetail.courseId
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '回复成功',
            icon: 'success'
          });
          this.setData({ replyContent: '' });
          // 重新加载回复列表
          this.getCommunications();
        }
      }
    });
  },

  // 加载讲师信息
  loadTeacherInfo(id) {
    wx.request({
      url: 'http://120.26.112.194:80/api/admin/courses/detailIntroduce',
      method: 'GET',
      data: {
        id: parseInt(id)
      },
      success: (res) => {
        console.log('讲师信息:', res.data);
        if (res.data && res.data.code === 200) {
          const teacherData = res.data.data[0];
          this.setData({
            teacherInfo: {
              consultantId: teacherData.consultantId,
              fullName: teacherData.fullName,
              consultantAvatar: teacherData.consultantAvatar,
              consultantGender: teacherData.consultantGender,
              consultantAge: teacherData.consultantAge,
              consultantAddress: teacherData.consultantAddress,
              consultantDesc: teacherData.consultantDesc,
              consultantIntroduction: teacherData.consultantIntroduction,
              consultantLevelId: teacherData.consultantLevelId,
              areaNames: teacherData.areaNames || '暂无擅长领域'
            }
          });
        } else {
          console.error('获取讲师信息失败:', res.data);
          wx.showToast({
            title: '获取讲师信息失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 咨询预约
  handleAppointment() {
    // 处理预约逻辑
    wx.navigateTo({
      url: '/pages/zhuye_detail/zixunyuyue/zixunyuyue'
    });
  },

  // 查看主页
  viewTeacherProfile() {
    const { teacherInfo } = this.data;
    if (teacherInfo && teacherInfo.consultantId) {
      wx.navigateTo({
        url: `/pages/zixun_detail/zixunshi/zixunshi?id=${teacherInfo.consultantId}`
      });
    }
  },

  // 立即沟通
  startChat() {
    const { teacherInfo } = this.data;
    if (teacherInfo && teacherInfo.consultantId) {
      // 处理沟通逻辑
      wx.showToast({
        title: '即将开始沟通',
        icon: 'none'
      });
    }
  },

  // 处理购买
  handleBuy() {
    const user = wx.getStorageSync('user');
    if (!user || !user.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 先检查是否已购买
    wx.request({
      url: `http://120.26.112.194:80/api/admin/courses/buyCheck?courseId=${this.data.courseId}&userId=${user.userId}`,
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          if (res.data.msg) {
            // 如果msg不为空，说明已购买
            wx.showToast({
              title: '您已购买过该课程',
              icon: 'none'
            });
          } else {
            // 未购买，显示确认购买框
            const price = this.data.courseDetail.discount ? 
              (this.data.courseDetail.originalPrice * this.data.courseDetail.discount).toFixed(2) : 
              this.data.courseDetail.originalPrice;
            
            wx.showModal({
              title: '确认购买',
              content: `确认支付 ￥${price} 购买该课程？`,
              success: (res) => {
                if (res.confirm) {
                  // 用户点击确认，执行购买
                  this.doBuy(user.userId);
                }
              }
            });
          }
        }
      },
      fail: () => {
        wx.showToast({
          title: '检查购买状态失败',
          icon: 'none'
        });
      }
    });
  },

  // 执行购买
  doBuy(userId) {
    wx.request({
      url: 'http://120.26.112.194:80/api/admin/courses/buy',
      method: 'POST',
      data: {
        userId: userId,
        courseId: this.data.courseId
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '购买成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.msg || '购买失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '购买失败',
          icon: 'none'
        });
      }
    });
  },

  // 显示分享弹窗
  showSharePopup() {
    this.setData({ showShare: true });
  },

  // 隐藏分享弹窗
  hideSharePopup() {
    this.setData({ showShare: false });
  },

  // 分享到微信好友
  shareToWechat() {
    wx.showToast({
      title: '分享到微信好友',
      icon: 'none'
    });
    this.hideSharePopup();
  },

  // 分享到朋友圈
  shareToMoments() {
    wx.showToast({
      title: '分享到朋友圈',
      icon: 'none'
    });
    this.hideSharePopup();
  },

  // 分享到QQ好友
  shareToQQ() {
    wx.showToast({
      title: '分享到QQ好友',
      icon: 'none'
    });
    this.hideSharePopup();
  },

  // 分享到QQ空间
  shareToQzone() {
    wx.showToast({
      title: '分享到QQ空间',
      icon: 'none'
    });
    this.hideSharePopup();
  },

  // 加载更多评价
  loadMoreReviews() {
    this.loadTypeData('reviews');
  },

  // 显示评价输入框
  showReviewInput() {
    this.setData({
      showReviewInput: true,
      newReview: {
        rating: 0,
        content: ''
      }
    });
  },

  // 隐藏评价输入框
  hideReviewInput() {
    this.setData({
      showReviewInput: false
    });
  },

  // 选择星级
  selectRating(e) {
    const rating = e.currentTarget.dataset.rating;
    this.setData({
      'newReview.rating': rating
    });
  },

  // 评价内容输入
  onReviewInput(e) {
    this.setData({
      'newReview.content': e.detail.value
    });
  },

  // 提交评价
  submitReview() {
    const { rating, content } = this.data.newReview;
    if (rating === 0) {
      wx.showToast({
        title: '请选择星级',
        icon: 'none'
      });
      return;
    }
    if (!content.trim()) {
      wx.showToast({
        title: '请输入评价内容',
        icon: 'none'
      });
      return;
    }

    const user = wx.getStorageSync('user');
    if (!user || !user.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 格式化当前时间为 yyyy-MM-dd HH:mm:ss
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

    wx.request({
      url: 'http://120.26.112.194:80/api/admin/courses/addReviews',
      method: 'POST',
      data: {
        userId: user.userId,
        courseId: this.data.courseId,
        courseRating: rating,
        reviewContent: content,
        reviewTime: formattedTime
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '评价成功',
            icon: 'success'
          });
          this.hideReviewInput();
          // 刷新评价列表
          this.loadTypeData('reviews');
        } else {
          wx.showToast({
            title: '评价失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '评价失败',
          icon: 'none'
        });
      }
    });
  },

  // 修改计算折扣价的方法
  getDiscountPrice() {
		const  courseDetail  = this.data.courseDetail;
		// 计算折扣价
		console.log(wx.getStorageSync('user'))
		const price = courseDetail.originalPrice * courseDetail.discount;
		this.setData({
			discountPrice:price.toFixed(2)
		})
    return discountPrice;
  },

  // 获取课程交流问题列表
  getCommunications(isLoadMore = false) {
    if (!this.data.hasMore && isLoadMore) return;
    if (this.data.isLoading) return;
    
    this.setData({ isLoading: true });
    
    const nextPage = isLoadMore ? this.data.currentPage + 1 : 1;
    
    wx.request({
      url: 'http://120.26.112.194:80/api/admin/courses/queryQuestion',
      method: 'GET',
      data: {
        courseId: this.data.courseDetail.courseId,
        page: nextPage,
        pageSize: this.data.pageSize
      },
      success: (res) => {
        if (res.data.code === 200) {
          const { list, hasNextPage } = res.data.data;
          
          this.setData({
            communications: isLoadMore ? [...this.data.communications, ...list] : list,
            hasMore: hasNextPage,
            currentPage: nextPage
          });
        }
      },
      fail: (err) => {
        console.error('获取问题列表失败:', err);
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  },

  // 格式化时间
  formatTime(timeStr) {
    const replyTime = new Date(timeStr);
    const now = new Date();
    const diff = now - replyTime;
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (hours < 24) {
      return `${hours}小时前`;
    } else if (days === 1) {
      return '昨天';
    } else {
      return `${replyTime.getFullYear()}-${String(replyTime.getMonth() + 1).padStart(2, '0')}`;
    }
  },

  // 获取问题回复列表
  getQuestionReplies(questionId, isLoadMore = false) {
    const courseId = this.data.courseDetail.courseId;
		
    wx.request({
      url: 'http://120.26.112.194:80/api/admin/courses/reply',
      method: 'GET',
      data: {
        questionId: questionId,
        courseId: courseId,
        page: isLoadMore ? this.data.currentPage + 1 : 1,
        pageSize: this.data.pageSize
      },
      success: (res) => {
        if (res.data.code === 200) {
          const newReplies = (res.data.data.list || []).map(reply => ({
            ...reply,
            formattedTime: this.formatTime(reply.replyTime)
          }));
          
          const communications = this.data.communications.map(item => {
            if (item.questionId === questionId) {
              return {
                ...item,
                replies: isLoadMore ? [...(item.replies || []), ...newReplies] : newReplies,
                showReplies: true,
                hasMore: res.data.data.hasNextPage
              };
            }
            return item;
          });
          this.setData({ 
            communications,
            currentPage: isLoadMore ? this.data.currentPage + 1 : 1
          });
        }
      }
    });
  },

  // 加载更多回复
  loadMoreReplies(e) {
		const questionId = e.currentTarget.dataset.id;
    this.getQuestionReplies(questionId, true);
  },

  // 切换回复列表显示状态
  toggleReplies(e) {
		const questionId = e.currentTarget.dataset.id;
		this.setData({
			tempQuestionId:questionId
		})
    const question = this.data.communications.find(item => item.questionId === questionId);
    
    if (!question) return;
    
    // 如果还没有获取过回复数据或replies未定义,则请求数据
    if (!question.replies || question.replies.length === 0) {
      this.getQuestionReplies(questionId);
    } else {
      // 否则只切换显示状态
      const communications = this.data.communications.map(item => {
        if (item.questionId === questionId) {
          return { ...item, showReplies: !item.showReplies };
        }
        return item;
      });
      this.setData({ communications });
    }
  },

  handleTabChange(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      classChooseIndex: index
    });
    
    // 切换到课堂交流标签时加载数据
    if (index === 3) {
      console.log('切换到课堂交流标签');
      this.getCommunications();
    }
  },

  // 显示回复输入框
  showReplyInput(e) {
    const questionId = e.currentTarget.dataset.id;
    this.setData({
      showReplyInput: true,
      currentQuestionId: questionId
    });
  },

  // 隐藏回复输入框
  hideReplyInput() {
    this.setData({
      showReplyInput: false,
      replyContent: '',
      currentQuestionId: null
    });
  },

  // 监听输入内容变化
  onReplyInput(e) {
    this.setData({
      replyContent: e.detail.value
    });
  },

  // 提交回复
  submitReply() {
    if (!this.data.replyContent.trim()) {
      wx.showToast({
        title: '请输入回复内容',
        icon: 'none'
      });
      return;
    }

    const user = wx.getStorageSync('user');
    if (!user) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '发送中...'
    });

    wx.request({
      url: 'http://http://120.26.112.194:80/api/admin/courses/collectadmin/courses/addReply',
      method: 'POST',
      data: {
        questionId: this.data.currentQuestionId,
        userId: user.userId,
        replyContent: this.data.replyContent
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '回复成功',
            icon: 'success'
          });
          
          // 重置页码并清空原有数据
          this.setData({
            currentPage: 1,
            hasMore: true
          }, () => {
						console.log(8888)
            // 重新请求数据，不传参数则默认 isLoadMore 为 false
            this.getQuestionReplies(this.data.tempQuestionId);
          });

          // 清空输入框并隐藏
          this.hideReplyInput();
        } else {
          wx.showToast({
            title: res.data.msg || '回复失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 添加点击加载更多方法
  loadMore() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.getCommunications(true);
    }
  },

  // 添加立即沟通方法
  chatWithTeacher() {
    console.log('咨询师信息:', this.data.teacherInfo);
    
    // 检查是否登录
    const user = wx.getStorageSync('user');
    if (!user) {
        wx.showToast({
            title: '请先登录',
            icon: 'none'
        });
        return;
    }

    // 确保有咨询师信息
    if (!this.data.teacherInfo || !this.data.teacherInfo.consultantId) {
        wx.showToast({
            title: '获取咨询师信息失败',
            icon: 'none'
        });
        return;
    }
    
    // 跳转到聊天页面
    wx.navigateTo({
        url: `/pages/kecheng_detail/chat/chat?consultantId=${this.data.teacherInfo.consultantId}&courseId=${this.data.courseId}`
    });
  }
})